﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
using SAC.Helper;
using DAL;
namespace BLL
{
    public class BLLValRep
    {
        static string xzTime = "2012-1-1";     //取值限制时间
        static string toExcel = "yes";         //导出Excel是否控制小数点
        string rtDBType = "";   //实时数据库
        string rlDBType = "";   //关系数据库

        DALRep dr = new DALRep();
        DALReport drp = new DALReport();
        DALValRep dvp = new DALValRep();
        ArrayList list = new ArrayList();
        StringBuilder sb = new StringBuilder();
        StrHelper sh = new StrHelper();
        DALUtilityMehtod um = new DALUtilityMehtod();

        StringBuilder show = new StringBuilder();
        StringBuilder hide = new StringBuilder();
        string body = "";

        /// <summary>
        /// 初始化函数
        /// </summary>
        private void init()
        {
            if (IniHelper.ReadIniData("Report", "XZTime", null) != "")
                xzTime = IniHelper.ReadIniData("Report", "XZTime", null);

            if (IniHelper.ReadIniData("Report", "Excle", null) != "")
                toExcel = IniHelper.ReadIniData("Report", "Excle", null);
        }

        /// <summary>
        /// 值报
        /// </summary>
        /// <param name="repName"></param>
        /// <param name="date"></param>
        /// <param name="unit"></param>
        /// <param name="repType"></param>
        /// <returns></returns>
        public string RetTableByVal(string repName, string date, string unit, string repType)
        {
            this.init();

            string sql = "";
            string qsrq = "";
            string jsrq = "";
            string bzID = "";
            string bName = "";
            string arrBZ = null;

            DateTime dtNow = DateTime.Now;
            bool isTrue = false;

            if (repType == "zr")
            {
                bName = "统计数据值日表";

                if (dtNow.Year == DateTime.Parse(date).Year && dtNow.Month == DateTime.Parse(date).Month && dtNow.Day == DateTime.Parse(date).Day)
                {
                    qsrq = DateTime.Parse(date).ToString("yyyy-MM-dd 0:00:00");
                    jsrq = dtNow.ToString("yyyy-MM-dd H:00:00"); isTrue = true;
                }
                else
                {
                    qsrq = DateTime.Parse(date).ToString("yyyy-MM-dd 0:00:00");
                    jsrq = DateTime.Parse(date).ToString("yyyy-MM-dd 23:59:59"); isTrue = false;
                }
            }
            else if (repType == "zy")
            {
                bName = "统计数据值月表";

                if (dtNow.Year == DateTime.Parse(date).Year && dtNow.Month == DateTime.Parse(date).Month)
                {
                    qsrq = DateTime.Parse(date).ToString("yyyy-MM-01 0:00:00");
                    jsrq = dtNow.AddDays(-1).ToString("yyyy-MM-dd 23:59:59"); isTrue = true;
                }
                else
                {
                    qsrq = DateTime.Parse(date).ToString("yyyy-MM-01 0:00:00");
                    jsrq = sh.LastDayOfMonth(DateTime.Parse(date)).ToString("yyyy-MM-dd 23:59:59"); isTrue = false;
                }
            }

            ArrayList list = dvp.RetArrsRepValDay(repType, repName, qsrq, jsrq, bName, unit, out bzID);

            string[] zb = (string[])list[0];
            string[] un = (string[])list[1];
            string[] lay = (string[])list[2];
            string[] dv = (string[])list[3];
            string[] dvExcel = (string[])list[4];

            ArrayList listOld = new ArrayList();
            ArrayList listDay = new ArrayList();

            ArrayList listYear = new ArrayList();
            ArrayList listMonth = new ArrayList();

            #region 报表
            if (toExcel == "yes")
                show.Append("<table width=\"98%\" border=\"1\" align=\"center\" class=\"bg\" valign=\"top\" bordercolorlight=\"#999999\" bordercolordark=\"#FFFFFF\" cellspacing=\"0\" cellpadding=\"1\" id=\"CX\">");
            else
                show.Append("<table width=\"98%\" border=\"1\" align=\"center\" class=\"bg\" valign=\"top\" bordercolorlight=\"#999999\" bordercolordark=\"#FFFFFF\" cellspacing=\"0\" cellpadding=\"1\" id=\"CX1\">");

            if (repType == "zr")
            {
                #region 日值
                sb.Append("<tr height='35px' bgcolor=\"#CFE6FC\"><td colspan=\"" + (4 + bzID.Split(',').Length - 1) + "\" style=\"font-size:20pt;font-weight:bold;height:40px;\" align=\"center\">" + repName + "日报表</td></tr>");
                sb.Append("<tr height='20px' bgcolor=\"#CFE6FC\" align=\"right\"><td colspan='" + (4 + bzID.Split(',').Length - 1) + "'>统计日期：" + date + "</td></tr>");
                sb.Append("<tr style=\"width: 80%;\" bgcolor=\"#CFE6FC\"> ");
                sb.Append("<td style=\"width: 20%;\">指 标 名 称</td>");
                sb.Append("<td style=\"width: 10%;\">单 位</td>");
                sb.Append("<td style=\"width: 10%;\">当 日</td>");
                sb.Append("<td style=\"width: 10%;\">环 比</td>");

                listOld = drp.RetArrsRepDay(repName, "日点", Convert.ToDateTime(qsrq).AddDays(-1).ToString(), Convert.ToDateTime(jsrq).AddDays(-1).AddSeconds(1).ToString(), isTrue);
                listDay = drp.RetArrsRepDay(repName, "日点", qsrq, Convert.ToDateTime(jsrq).AddSeconds(1).ToString(), isTrue);


                string[] bz = bzID.Split(',');
                for (int i = 0; i < bz.Length - 1; i++)
                {
                    string bzs = getValueName(bz[i]);

                    sb.AppendFormat("<td bgcolor=\"#CFE6FC\" align='center'>{0}</td>", bzs);
                }

                sb.Append("</tr>");

                for (int i = 1; i < zb.Length; i++)
                {
                    sb.AppendFormat("<tr><td bgcolor=\"#CFE6FC\" align='center'>{0}</td>", zb[i]);
                    sb.AppendFormat("<td bgcolor=\"#CFE6FC\" align='center'>{0}</td>", un[i]);

                    if (((string[])listDay[3])[i] != null)
                    {
                        double valuenew = Convert.ToDouble(((string[])listDay[3])[i].ToString().Split(',')[Convert.ToInt32(unit) - 1]);
                        double valueold = Convert.ToDouble(((string[])listOld[3])[i].ToString().Split(',')[Convert.ToInt32(unit) - 1]);
                        double values = valuenew - valueold;

                        values = getDouble(Convert.ToDouble(values), 2);

                        sb.AppendFormat("<td align='right'>{0}</td>", valuenew);

                        sb.AppendFormat("<td align='right'>{0}</td>", values);
                    }
                    else
                    {
                        sb.Append("<td align='right'>&nbsp;</td>");

                        sb.Append("<td align='right'>&nbsp;</td>");
                    }

                    if (dv[i] != null)
                    {
                        string[] str = dv[i].Split(',');

                        for (int k = 0; k < str.Length - 1; k++)
                        {
                            sb.AppendFormat("<td align='right'>{0}</td>", str[k]);
                        }
                    }
                    else
                    {
                        for (int k = 0; k < 3; k++)
                        {
                            sb.AppendFormat("<td align='right'>{0}</td>", "&nbsp;");
                        }
                    }

                    sb.Append("</tr>");

                }
                #endregion
            }
            else if (repType == "zy")
            {
                #region 月值
                sb.Append("<tr height='35px' bgcolor=\"#CFE6FC\"><td colspan='" + (9) + "' style=\"font-size:20pt;font-weight:bold;height:40px;\" align=\"center\">" + repName + "</td></tr>");
                sb.Append("<tr height='20px' bgcolor=\"#CFE6FC\" align=\"right\"><td colspan='" + (zb.Length + 1) + "'>统计日期：" + date + "</td></tr>");
                sb.Append("<tr style=\"width: 80%;\" bgcolor=\"#CFE6FC\"> ");
                sb.Append("<td style=\"width: 20%;\">指 标 名 称</td>");
                sb.Append("<td style=\"width: 10%;\">单  位</td>");
                sb.Append("<td style=\"width: 10%;\">年累计</td>");
                sb.Append("<td style=\"width: 10%;\">月累计</td>");

                listMonth = drp.RetArrsRepMonth(repName, "月报", "月点", qsrq, Convert.ToDateTime(jsrq).AddSeconds(1).ToString(), qsrq, Convert.ToDateTime(qsrq).AddMonths(1).ToShortDateString(), isTrue);
                if (Convert.ToDateTime(date).Year == DateTime.Now.Year)
                    isTrue = true;
                else
                    isTrue = false;
                listYear = drp.RetArrsRepMonth(repName, "年报", "月点", Convert.ToDateTime(qsrq).Year + "-" + "01-01 0:00:00.0", Convert.ToDateTime(jsrq).AddSeconds(1).ToString(), Convert.ToDateTime(qsrq).Year + "-" + "01-01 0:00:00.0", (Convert.ToDateTime(qsrq).Year + 1) + "-" + "01-01 0:00:00.0", isTrue);

                string[] bz = bzID.Split(',');
                for (int i = 0; i < bz.Length - 1; i++)
                {
                    string bzs = getValueName(bz[i]);
                    sb.AppendFormat("<td bgcolor=\"#CFE6FC\" align='center'>{0}</td>", bzs + "月累计");
                }

                sb.Append("</tr>");

                for (int i = 1; i < zb.Length; i++)
                {
                    sb.AppendFormat("<tr><td bgcolor=\"#CFE6FC\" align='center'>{0}</td>", zb[i]);
                    sb.AppendFormat("<td bgcolor=\"#CFE6FC\" align='center'>{0}</td>", un[i]);

                    #region 年累计
                    string valueYear = "";
                    double value = 0;
                    if (listYear != null && listYear.Count != 0)
                        if (((string[])listYear[3])[i] != null && ((string[])listYear[3])[i] != "")
                        {
                            valueYear = ((string[])listYear[3])[i].ToString().Split(',')[Convert.ToInt32(unit) - 1];
                            value = getDouble(Convert.ToDouble(valueYear), 2);
                            sb.AppendFormat("<td align='right'>{0}</td>", value);
                        }
                        else
                        {
                            sb.Append("<td align='right'>&nbsp;</td>");
                        }
                    else
                        sb.Append("<td align='right'>&nbsp;</td>");
                    #endregion

                    #region 月累计
                    string valueMonth = "";
                    if (((string[])listMonth[3])[i] != null && ((string[])listMonth[3])[i] != "")
                    {
                        valueMonth = ((string[])listMonth[3])[i].ToString().Split(',')[Convert.ToInt32(unit) - 1];
                        value = getDouble(Convert.ToDouble(valueMonth), 2);
                        sb.AppendFormat("<td align='right'>{0}</td>", value);
                    }
                    else
                    {
                        sb.Append("<td align='right'>&nbsp;</td>");
                    }
                    #endregion

                    #region 月值
                    if (dv[i] != null)
                    {
                        string[] str = dv[i].Split(',');

                        for (int k = 0; k < str.Length - 1; k++)
                        {
                            sb.AppendFormat("<td align='right'>{0}</td>", str[k]);
                        }
                    }
                    #endregion

                    sb.Append("</tr>");

                }
                #endregion
            }
            sb.Append("</table>");
            #endregion

            #region 导出Excel表
            if (toExcel == "no")
                hide.Append("<table width=\"90%\" border=\"1\" align=\"center\" class=\"bg\" valign=\"top\" bordercolorlight=\"#999999\" bordercolordark=\"#FFFFFF\" cellspacing=\"0\" cellpadding=\"1\" id=\"CX\" style=\"display:none;\">");
            else
                hide.Append("<table width=\"90%\" border=\"1\" align=\"center\" class=\"bg\" valign=\"top\" bordercolorlight=\"#999999\" bordercolordark=\"#FFFFFF\" cellspacing=\"0\" cellpadding=\"1\" id=\"CX1\" style=\"display:none;\">");
            body = sb.ToString();
            sb = new StringBuilder();
            sb.Append(show.ToString() + body + hide.ToString() + body);
            #endregion
            string result = "";
            result = zb.Length + "," + sb.ToString();
            return result;
            //return sb.ToString();
        }


        /// <summary>
        ///  设备投退监视
        /// </summary>
        /// <param name="id"></param>
        /// <param name="sTime"></param>
        /// <param name="eTime"></param>
        /// <returns></returns>
        public string getQTjs(string id, DateTime sTime, DateTime eTime)
        {
            this.init();
            DataTable dt = new DataTable();
            dt = dvp.getQTjs(id, sTime, eTime);

            if (toExcel == "yes")
                show.Append("<table width=\"98%\" border=\"1\" align=\"center\" class=\"bg\" valign=\"top\" bordercolorlight=\"#999999\" bordercolordark=\"#FFFFFF\" cellspacing=\"0\" cellpadding=\"1\" id=\"CX\">");
            else
                show.Append("<table width=\"98%\" border=\"1\" align=\"center\" class=\"bg\" valign=\"top\" bordercolorlight=\"#999999\" bordercolordark=\"#FFFFFF\" cellspacing=\"0\" cellpadding=\"1\" id=\"CX1\">");

            sb.Append("<tr height='35px' bgcolor=\"#CFE6FC\"><td colspan='3' style=\"font-size:20pt;font-weight:bold;height:40px;\" align=\"center\">" + "投退时间纪录" + "</td></tr>");
            sb.Append("<tr height='20px' bgcolor=\"#CFE6FC\" align=\"right\"><td colspan='3'>统计时间：" + DateTime.Now.ToString() + "</td></tr>");
            sb.Append("<tr style=\"width: 80%;\" bgcolor=\"#CFE6FC\"> ");
            sb.Append("<td style=\"width: 20%;\">设备名称</td>");
            sb.Append("<td style=\"width: 10%;\">起始时间</td>");
            sb.Append("<td style=\"width: 10%;\">结束时间</td>");
            sb.Append("</tr>");

            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string name = "&nbsp;";
                    string startTime = "&nbsp";
                    string endTime = "&nbsp";
                    if (dt.Rows[i]["设备名称"] != null && dt.Rows[i]["设备名称"].ToString() != "")
                        name = dt.Rows[i]["设备名称"].ToString();
                    if (dt.Rows[i]["起始时间"] != null && dt.Rows[i]["起始时间"].ToString() != "")
                        startTime = dt.Rows[i]["起始时间"].ToString();
                    if (dt.Rows[i]["结束时间"] != null && dt.Rows[i]["结束时间"].ToString() != "")
                        endTime = dt.Rows[i]["结束时间"].ToString();
                    sb.Append("<tr>");
                    sb.AppendFormat("<td style=\"width: 20%;\">{0}</td>", name);
                    sb.AppendFormat("<td style=\"width: 10%;\">{0}</td>", startTime);
                    sb.AppendFormat("<td style=\"width: 10%;\">{0}</td>", endTime);
                    sb.Append("</tr>");
                }
            }
            sb.Append("</table>");

            #region 导出Excel表
            if (toExcel == "no")
                hide.Append("<table width=\"90%\" border=\"1\" align=\"center\" class=\"bg\" valign=\"top\" bordercolorlight=\"#999999\" bordercolordark=\"#FFFFFF\" cellspacing=\"0\" cellpadding=\"1\" id=\"CX\" style=\"display:none;\">");
            else
                hide.Append("<table width=\"90%\" border=\"1\" align=\"center\" class=\"bg\" valign=\"top\" bordercolorlight=\"#999999\" bordercolordark=\"#FFFFFF\" cellspacing=\"0\" cellpadding=\"1\" id=\"CX1\" style=\"display:none;\">");
            body = sb.ToString();
            sb = new StringBuilder();
            sb.Append(show.ToString() + body + hide.ToString() + body);
            #endregion

            string reslut = "";
            reslut = (dt.Rows.Count + 1) + "," + sb.ToString();
            return reslut;
            //return sb.ToString();
        }

        /// <summary>
        /// 机组事件查询
        /// </summary>
        /// <param name="id"></param>
        /// <param name="sTime"></param>
        /// <param name="eTime"></param>
        /// <returns></returns>
        public string getJzSj(int id, string sTime, string eTime)
        {
            this.init();
            DataTable dt = new DataTable();
            dt = dvp.getJzSj(id, sTime, eTime);

            if (toExcel == "yes")
                show.Append("<table width=\"98%\" border=\"1\" align=\"center\" class=\"bg\" valign=\"top\" bordercolorlight=\"#999999\" bordercolordark=\"#FFFFFF\" cellspacing=\"0\" cellpadding=\"1\" id=\"CX\">");
            else
                show.Append("<table width=\"98%\" border=\"1\" align=\"center\" class=\"bg\" valign=\"top\" bordercolorlight=\"#999999\" bordercolordark=\"#FFFFFF\" cellspacing=\"0\" cellpadding=\"1\" id=\"CX1\">");

            sb.Append("<tr height='35px' bgcolor=\"#CFE6FC\"><td colspan='6'>" + "机组运行小时查询" + "</td></tr>");
            sb.Append("<tr height='20px' bgcolor=\"#CFE6FC\" align=\"right\"><td colspan='6'>查询时间：" + DateTime.Now.ToString() + "</td></tr>");
            sb.Append("<tr style=\"width: 80%;\" bgcolor=\"#CFE6FC\"> ");
            sb.Append("<td rowspan=\"2\">序    号</td>");
            sb.Append("<td rowspan=\"2\">机组编号</td>");
            sb.Append("<td colspan=\"2\">事件状态起止时间</td>");
            sb.Append("<td rowspan=\"2\">事件持续小时</td>");
            sb.Append("<td rowspan=\"2\">事件原因补充说明</td>");
            sb.Append("</tr>");
            sb.Append("<tr bgcolor=\"#CFE6FC\"> ");
            sb.Append("<td>起始时间</td>");
            sb.Append("<td>终止时间</td>");
            sb.Append("</tr>");

            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string startTime = "&nbsp";
                    string endTime = "&nbsp";
                    string active = "&nbsp";
                    string hour = "&nbsp";
                    if (dt.Rows[i]["起始时间"] != null && dt.Rows[i]["起始时间"].ToString() != "")
                        startTime = dt.Rows[i]["起始时间"].ToString();
                    if (dt.Rows[i]["结束时间"] != null && dt.Rows[i]["结束时间"].ToString() != "")
                        endTime = dt.Rows[i]["结束时间"].ToString();
                    if (dt.Rows[i]["事件原因补充说明"] != null && dt.Rows[i]["事件原因补充说明"].ToString() != "")
                        active = dt.Rows[i]["事件原因补充说明"].ToString();
                    if (dt.Rows[i]["事件持续小时"] != null && dt.Rows[i]["事件持续小时"].ToString() != "")
                        hour = dt.Rows[i]["事件持续小时"].ToString();
                    sb.Append("<tr>");
                    sb.AppendFormat("<td style=\"width: 10%;\">{0}</td>", i + 1);
                    sb.AppendFormat("<td style=\"width: 10%;\">{0}</td>", dt.Rows[i]["机组编号"]);
                    sb.AppendFormat("<td style=\"width: 30%;\">{0}</td>", startTime);
                    sb.AppendFormat("<td style=\"width: 30%;\">{0}</td>", endTime);
                    sb.AppendFormat("<td style=\"width: 10%;\">{0}</td>", hour);
                    sb.AppendFormat("<td style=\"width: 10%;\">{0}</td>", active);
                    sb.Append("</tr>");
                }
            }
            sb.Append("</table>");

            #region 导出Excel表
            if (toExcel == "no")
                hide.Append("<table width=\"90%\" border=\"1\" align=\"center\" class=\"bg\" valign=\"top\" bordercolorlight=\"#999999\" bordercolordark=\"#FFFFFF\" cellspacing=\"0\" cellpadding=\"1\" id=\"CX\" style=\"display:none;\">");
            else
                hide.Append("<table width=\"90%\" border=\"1\" align=\"center\" class=\"bg\" valign=\"top\" bordercolorlight=\"#999999\" bordercolordark=\"#FFFFFF\" cellspacing=\"0\" cellpadding=\"1\" id=\"CX1\" style=\"display:none;\">");
            body = sb.ToString();
            sb = new StringBuilder();
            sb.Append(show.ToString() + body + hide.ToString() + body);
            #endregion
            string result = "";
            result = dt.Rows.Count + 1 + "," + sb.ToString();
            return result;
            //return sb.ToString();
        }

        /// <summary>
        /// 获取投退设备集合
        /// </summary>
        /// <returns></returns>
        public IList<Hashtable> getQTPoint()
        {
            IList<Hashtable> list = null;
            DataTable dt = dvp.getQTPoint();
            list = DataTableToList(dt);
            return list;
        }

        /// <summary>
        /// 获取机组数据
        /// </summary>
        /// <returns></returns>
        public IList<Hashtable> getJz()
        {
            IList<Hashtable> list = null;
            DataTable dt = dvp.getJz();
            list = DataTableToList(dt);
            return list;
        }

        #region 从DataTable转化为List
        /// <summary>
        /// 从DataTable转化为List
        /// </summary>
        /// <param name="dt">数据集</param>
        /// <returns>List集合</returns>
        public static IList<Hashtable> DataTableToList(DataTable dt)
        {
            IList<Hashtable> list = null;
            if (dt != null && dt.Rows.Count > 0)
            {
                list = new List<Hashtable>();
                Hashtable ht = null;
                foreach (DataRow row in dt.Rows)
                {
                    ht = new Hashtable();
                    foreach (DataColumn col in dt.Columns)
                    {
                        if (row[col.ColumnName] != null && !string.IsNullOrEmpty(Convert.ToString(row[col.ColumnName])))
                        {
                            ht.Add(col.ColumnName.ToUpper(), row[col.ColumnName]);
                        }
                        else
                        {
                            ht.Add(col.ColumnName.ToUpper(), "");
                        }
                    }
                    list.Add(ht);
                }
            }
            return list;
        }
        #endregion

        #region 班值名称
        private static string getValueName(string id)
        {
            string name = "";
            if (id == "1")
            {
                name = "一值";
            }
            else if (id == "2")
            {
                name = "二值";
            }
            else if (id == "3")
            {
                name = "三值";
            }
            else if (id == "4")
            {
                name = "四值";
            }
            else if (id == "5")
            {
                name = "五值";
            }
            else if (id == "6")
            {
                name = "六值";
            }
            else if (id == "7")
            {
                name = "七值";
            }
            return name;
        }
        #endregion

        #region 四舍五入
        /// <summary>
        /// 四舍五入
        /// </summary>
        /// <param name="result">要转换的数值</param>
        /// <param name="num">保留位数</param>
        /// <returns></returns>
        public double getDouble(double result, int num)
        {
            string res = result.ToString();
            string results = "";
            int index = res.IndexOf('.');

            if (index > 0)
            {
                index += num;
                res += "0000000000000000";
                res = res.Remove(0, index + 1);
                results = result + "0000000000000000000";
                results = results.Substring(0, index + 1);
                res = res.Substring(0, 1);

                string point = "0.";

                for (int count = 0; count < num - 1; count++)
                {
                    point += "0";
                }
                point += "1";


                if (Convert.ToDouble(res) > 4)
                {
                    results = (Convert.ToDouble(results) + Convert.ToDouble(point)).ToString();
                    res = results;
                }
                else
                {
                    res = results;
                }
            }
            else
            {
                res += ".";
                for (int i = 0; i < num; i++)
                {
                    res += "0";
                }
            }
            return Convert.ToDouble(res);
        }
        #endregion

    }
}
